#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/SimpleDB'
require 'basic_configuration'
require 'aws_context'
require 'pp'

# Create or update a SimpleDB item's attributes

if ARGV[0] == '-?' || ARGV.size < 2 then
  puts "usage: put-attributes domain-name item-name [-r] [attribute:value]+"
  exit 1
end
domain_name = ARGV[0]
item_name = ARGV[1]
replace = false
attributes = {}
ARGV.shift; ARGV.shift
ARGV.each do |arg|
  if arg == '-r' 
    replace = true
  else
    av = arg.split(':', 2)
    if av.size != 2 
      puts "error: attribute has no value #{arg}"
    else
      attributes.merge!({av[0] => av[1]})
    end
  end
end
if attributes.length == 0
  puts "error: no attribte:value"
  exit 1
end

Signal.trap("INT") do
  exit 2
end

config = BasicConfiguration.new
sdb = AwsContext.instance.sdb(*config.keys)
begin
  res = sdb.put_attributes(domain_name, item_name, attributes, replace)
rescue
  puts "error #{$!} #{domain_name} #{item_name}"
  exit 1
end

